package com.cook.service.impl;

import com.cook.mapper.AdminMapper;
import com.cook.service.AdminService;
import com.cook.vo.admin.ALLUserVO;
import com.cook.vo.admin.AllUserDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    public Map<String, Object> getAllUsersWithPage(Integer pageNum, Integer pageSize) {
        log.info("分页查询所有用户: pageNum={}, pageSize={}", pageNum, pageSize);

        validatePageParams(pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<ALLUserVO> userList = adminMapper.selectAllUsersWithPage(offset, pageSize);
            int totalCount = adminMapper.selectUserTotalCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", userList);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("分页查询成功，共 {} 条数据，总页数: {}", userList.size(), totalPages);
            return result;

        } catch (Exception e) {
            log.error("分页查询用户列表失败: ", e);
            throw new RuntimeException("查询用户列表失败");
        }
    }

    public AllUserDetailVO getUserDetailById(Long userId) {
        log.info("查询用户详情: userId={}", userId);

        try {
            AllUserDetailVO userDetail = adminMapper.selectUserDetailById(userId);
            if (userDetail == null) {
                log.warn("用户不存在: userId={}", userId);
                throw new RuntimeException("用户不存在");
            }
            log.info("查询用户详情成功: userId={}", userId);
            return userDetail;
        } catch (Exception e) {
            log.error("查询用户详情失败: userId={}", userId, e);
            throw new RuntimeException("查询用户详情失败");
        }
    }

    @Transactional
    public boolean deleteUser(Long userId) {
        log.info("删除用户: userId={}", userId);

        try {
            int result = adminMapper.deleteUserById(userId);
            boolean success = result > 0;

            if (success) {
                log.info("用户删除成功: userId={}", userId);
            } else {
                log.warn("用户删除失败: userId={}", userId);
            }

            return success;
        } catch (Exception e) {
            log.error("删除用户失败: userId={}", userId, e);
            throw new RuntimeException("删除用户失败");
        }
    }

    public Map<String, Object> searchUsers(String keyword, Integer pageNum, Integer pageSize) {
        log.info("搜索用户: keyword={}, pageNum={}, pageSize={}", keyword, pageNum, pageSize);

        validatePageParams(pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<ALLUserVO> userList = adminMapper.searchUsers(keyword, offset, pageSize);
            int totalCount = adminMapper.searchUsersCount(keyword);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", userList);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);
            result.put("keyword", keyword);

            log.info("搜索成功，共 {} 条数据", userList.size());
            return result;
        } catch (Exception e) {
            log.error("搜索用户失败: keyword={}", keyword, e);
            throw new RuntimeException("搜索用户失败");
        }
    }

    public int getUserTotalCount() {
        log.info("查询用户总数");

        try {
            int count = adminMapper.selectUserTotalCount();
            log.info("用户总数: {}", count);
            return count;
        } catch (Exception e) {
            log.error("查询用户总数失败: ", e);
            throw new RuntimeException("查询用户总数失败");
        }
    }

    /**
     * 验证分页参数
     */
    private void validatePageParams(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum <= 0) {
            throw new IllegalArgumentException("页码必须大于0");
        }
        if (pageSize == null || pageSize <= 0 || pageSize > 100) {
            throw new IllegalArgumentException("每页数量必须在1-100之间");
        }
    }

}
